<?php
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
$myPdo = DbUtils::createPdoInst();
$page_id = MiscUtils::getParam('i', NULL);
$item_id = MiscUtils::getParam('id', 0);
$instance_id = MiscUtils::getParam('inid', 0);

$item = NULL;
$addrs = array();

$cond_vals = new stdClass();
$cond_vals->c = 't.id = :v1';
$cond_vals->v = array(':v1' => $item_id);
$tmp = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
if (count($tmp) > 0) {
  $item = $tmp[0];
  $cond_vals = new stdClass();
	$cond_vals->c = 't.customer_id = :v1';
	$cond_vals->v = array(':v1' => $item->id);
	$addrs = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer_addr', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
}

$opts = new stdClass();
$opts->select_expr = 'MIN(t.customer_id) AS min_id';
$min_id = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer_addr', NULL, NULL, NULL, NULL, NULL, $opts)->d[0]->min_id;
$min_id = min(0, $min_id);
--$min_id;

$members = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer_member', NULL, 't.total_spent', 'ASC', NULL, NULL, NULL)->d;
$status = array();
$s1 = new stdClass();
$s1->id = 0;
$s1->name = 'Inactivated';
$s2 = new stdClass();
$s2->id = 1;
$s2->name = 'Activated';
$s3 = new stdClass();
$s3->id = 2;
$s3->name = 'Suspended';
array_push($status, $s1, $s2, $s3);


function _getIP(){ 
  if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
    $ip = getenv("HTTP_CLIENT_IP"); 
  } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
    $ip = getenv("HTTP_X_FORWARDED_FOR"); 
  } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
    $ip = getenv("REMOTE_ADDR"); 
  } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
    $ip = $_SERVER['REMOTE_ADDR']; 
  } else {
    $ip = "unknown";
  }
  return($ip);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
* {
  font-family: Trebuchet MS;
  font-size: 12px;
  padding: 0;
  margin: 0;
}
table.form {
  background-color: #fff;
  border-top: 1px solid #222;
  border-left: 1px solid #222;
}
table.form th.header {
  text-align: left;
  color: #fff;
  background-color: #222;
  padding-left: 5px;
  font-weight: bold;
  height: 25px;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
}
table.form td {
  vertical-align: middle;
}
table.form td.title {
  background-color: #666;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
  width: 150px;
  color: #fff;
  padding: 3px 5px; 
  vertical-align: top;
  font-weight: bold;
}
table.form td.content {
  padding-left: 2px;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
}
table.form td.content input[type=text],input[type=password],textarea,select,option {
  width: 98%;
  border: 0;
  padding: 0;
  margin: 0;
}
table.form td.content select {
  border: 1px solid #ddd;
}
table.form td.content input[type=text],input[type=password] {
  height: 20px;
}
table.form td.content textarea {
  height: 50px;
  resize: none;
}
table.form2 {
  background-color: #fff;
  border-top: 1px solid #999;
  border-left: 1px solid #999;
}
table.form2 td {
  vertical-align: middle;
}
table.form2 td.title {
  background-color: #ddd;
  border-bottom: 1px solid #999;
  border-right: 1px solid #999;
  width: 150px;
  padding: 3px 5px; 
  vertical-align: top;
}
table.form2 td.content {
  padding-left: 2px;
  border-bottom: 1px solid #999;
  border-right: 1px solid #999;
}
table.form2 td.content input[type=text],input[type=password],textarea,select,option {
  width: 98%;
  border: 0;
  padding: 0;
  margin: 0;
}
table.form2 td.content input[type=text],input[type=password] {
  height: 20px;
}
table.form2 td.content textarea {
  height: 50px;
  resize: none;
}
table.list {
  border-left: 1px solid #666;
  border-top: 1px solid #666;
  font-size: 12px;
  width: 99%;
  margin-bottom: 5px;
}
table.list tr.sort td {
  text-align: left;
  height: 28px;
  background-color: #ddd;
  padding: 0 5px; 
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  font-weight: bold;
  vertical-align: middle;
  cursor: pointer;
}
table.list th.nosort {
  text-align: left;
  height: 28px;
  background-color: #ddd;
  padding: 0 5px; 
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  font-weight: bold;
  vertical-align: middle;
}
table.list tr.rowodd td {
  padding: 0 5px;
  height: 25px;
  background-color: #eee;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
  vertical-align: middle;
}
table.list tr.roweven td {
  padding: 0 5px;
  height: 25px;
  background-color: #fff;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
  vertical-align: middle;
}
table.list tr.rowodd:hover td {
  background-color: #f4f3b2;
}
table.list tr.roweven:hover td {
  background-color: #f4f3b2;
}
table.list tr.none td {
  padding: 0 5px;
  height: 25px;
  background-color: #fff;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
}
.imgbtn {
  background-image: url(assets/imgs/save.png);
  background-repeat: no-repeat;
  background-position: 5px 2px;
  padding: 5px 5px 5px 30px;
  border: 1px solid #666;
  background-color: #fff;
  cursor: pointer;
  border-radius: 3px;
}
.imgbtn:hover {
  background-color: #eee;
}

.ok {
  background-image: url(assets/imgs/ok.png);
  background-size: 24px 24px;
  width: 80px;
}
.cancel {
  background-image: url(assets/imgs/cancel.png);
  background-size: 24px 24px;
  margin-left: 5px;
  width: 80px;
}

.add {
  background-image: url(assets/imgs/add16.png) !important;
  padding: 2px 2px 2px 20px !important;
  margin: 2px 0 !important;
}
.add2 {
  background-image: url(assets/imgs/add16_2.png) !important;
  padding: 2px 2px 2px 20px  !important;
}
.imgico {
  cursor: pointer;
}
ul.hztl li {
  display: inline;
  vertical-align: middle;
}
</style>
</head>
<body>
<div>
  <table class="form" style="width: 950px;" cellpadding=0 cellspacing=0>
    <tr><th class="header" colspan=2>Edit Customer</th></tr>
    <tr>
      <td class="title">Account</td>
      <td class="content"><input onchange="CheckUtils.addToArray(_checks_add, this, check_account, _errors_add);" value="<?php echo (($item) ? $item->account : ''); ?>" id="account" type="text"></input></td>
    </tr>
    <tr>
      <td class="title">Password</td>
      <td class="content"><input value="<?php echo (($item) ? $item->password : ''); ?>" onchange="_pwchg = 1;" id="password" type="password"></input></td>
    </tr>
    <tr>
      <td class="title">First Name</td>
      <td class="content"><input value="<?php echo (($item) ? $item->first_name : ''); ?>" id="first_name" type="text"></input></td>
    </tr>
    <tr>
      <td class="title">Last Name</td>
      <td class="content"><input value="<?php echo (($item) ? $item->last_name : ''); ?>" id="last_name" type="text"></input></td>
    </tr>
    <tr>
      <td class="title">Phone</td>
      <td class="content"><input value="<?php echo (($item) ? $item->phone : ''); ?>" id="phone" type="text"></input></td>
    </tr>
    <tr>
      <td class="title">Status</td>
      <td class="content"><select id="active_select"></select></td>
    </tr>
    <tr>
      <td class="title">Membership</td>
      <td class="content"><select id="member_select"></select></td>
    </tr>
    <tr style="display: none;">
      <td class="title">IP</td>
      <td class="content"><input value="<?php echo (($item) ? $item->ip : _getIP()); ?>" id="ip" type="text"></input></td>
    </tr>
    <tr style="display: none;">
      <td class="title">IP Place</td>
      <td class="content"><input value="<?php echo (($item) ? $item->ip_place : ''); ?>" id="ip_place" type="text"></input></td>
    </tr>
    <tr id="addr_btn_div" style="<?php echo (!$item) ? 'display: table-row' : ''?>">
	    <td class="title">Addresses</td>
	    <td class="content">
	      <button class="imgbtn add" onclick="save_addr(null, this);">New Addr</button>
				<div>
				  <table class="list" cellPadding="0" cellSpacing="0" id="addr_table">
				    <tr>
				      <th class="nosort" width="45px">Default</th>
				      <th class="nosort" width="100px">First Name</th>
				      <th class="nosort" width="100px">Last Name</th>
				      <th class="nosort">Address</th>
              <th class="nosort" width="100px">City</th>
				      <th class="nosort" width="40px"></th>
				    </tr>
				  </table>
				</div>
	    </td>
	  </tr>
  </table>
  <button class="imgbtn" onclick="check_save();" style="margin-top: 5px;">Save</button>
  <div style="height: 200px"></div>
</div>
<script type="text/javascript" src="../../../libs/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script type="text/javascript" src="../../../incls/js/checkutils.js"></script>
<script type="text/javascript" src="pop/pop.js"></script>
<script type="text/javascript" src="assets/js/addr.js"></script>
<script type="text/javascript">
  var _item = JSON.parse('<?php echo addslashes(json_encode($item)); ?>');
  var _addrs = JSON.parse('<?php echo isset($addrs) ? addslashes(json_encode($addrs)) : '[]'; ?>');
  var _members = JSON.parse('<?php echo addslashes(json_encode($members)); ?>');
  var _status = JSON.parse('<?php echo addslashes(json_encode($status)); ?>');
  var _pwchg = 0;
  var _checks_add = [];
  var _errors_add = [];
  
  $(function(){
    //NOT GOOD
    parent.document.getElementById('real_last').style.display = 'block';
    
    var div = parent.document.getElementById('<?php echo LAST_NAV; ?>');
    var div_parent = div.parentNode;
    MyUtils.removeChildElements(div_parent);
    var elm;
    elm = parent.document.createElement('a');
    elm.href = '#';
    elm.style.color = '#000';
    elm.style.fontSize = '13px';
    elm.style.fontWeight = 'bold';
    elm.onclick = function() {
      var url = parent.document.URL.replace('&script=index_customer', '');
      url = url.replace('&id=<?php echo $item_id; ?>', '');
      url = url.replace('#', '');
      parent.location.href = url;
    };
    elm.appendChild(parent.document.createTextNode('Customers'));
    div_parent.appendChild(elm);

    var td;
    td = div_parent.parentNode.insertCell(-1);
    td.style.width = '20px';
    td.style.textAlign = 'center';
    td.style.color = '#aaa';
    td.appendChild(parent.document.createTextNode('>'));
    
    td = div_parent.parentNode.insertCell(-1);
    td.style.height = '25px';
    td.style.color = '#333';
    td.style.fontSize = '13px';
    if (_item && _item.id) {
      td.appendChild(parent.document.createTextNode(MyUtils.getShort(_item.account, 12)));
    } else {
      td.appendChild(parent.document.createTextNode('New Customer'));
    }
    //NOT GOOD END
    
    set_member();
    set_status();
    set_customer_addr();
  });

  function set_member() {
    var m_sel = $('#member_select')[0];
    for (var i in _members) {
      var member = _members[i];
      var opt = new Option(member.title, member.id);
      m_sel.options[m_sel.options.length] = opt;
      if (_item && _item.member_id == member.id) {
        m_sel.selectedIndex = m_sel.options.length - 1;
      }
    }
  };

  function set_status() {
    var a_sel = $('#active_select')[0];
    for (var i in _status) {
      var tmp = _status[i];
      var opt = new Option(tmp.name, tmp.id);
      a_sel.options[a_sel.options.length] = opt;
      if (_item && _item.is_actived == tmp.id) {
        a_sel.selectedIndex = a_sel.options.length - 1;
      }
    }
  };
  
  function set_customer_addr() {
    var table = document.getElementById('addr_table');
    MyUtils.removeTableRows(table, 1);

    if (_addrs.length == 0) {
      var tr = table.insertRow(-1);
      tr.className = 'none';
      var td = tr.insertCell(-1);
      td.colSpan=6;
      td.appendChild(document.createTextNode('No Results'));
    }
    for (var i = 0; i < _addrs.length; i++) {
      var addr = _addrs[i];
      
      var tr = table.insertRow(-1);
      tr.className = (i % 2 == 0) ? 'roweven' : 'rowodd';
      var td = tr.insertCell(-1);
	    var input = document.createElement('input');
	    input.type = 'radio';
	    input.name = 'default';
	    input.checked = (addr.is_default == 1);
	    input._addr = addr;
	    input.onclick = function() {
	      set_addr_default(this._addr);
	    }
	    td.appendChild(input);
      var td = tr.insertCell(-1);
      td.title = addr.name;
      td.appendChild(document.createTextNode(MyUtils.getShort(addr.first_name, 20)));
      var td = tr.insertCell(-1);
      td.title = addr.tel;
      td.appendChild(document.createTextNode(MyUtils.getShort(addr.last_name, 20)));
      var td = tr.insertCell(-1);
      td.title = addr.street;
      td.appendChild(document.createTextNode(MyUtils.getShort(addr.address1, 30)));
      var td = tr.insertCell(-1);
      td.title = addr.street;
      td.appendChild(document.createTextNode(MyUtils.getShort(addr.city, 30)));
      var td = tr.insertCell(-1);
      var img1 = document.createElement('img');
      img1.className = 'imgico';
      img1.src = 'assets/imgs/edit.png';
      img1._addr = addr;
      img1.onclick = function() {
        save_addr(this._addr, this);
      }
      td.appendChild(img1);
      var img2 = document.createElement('img');
      img2.className = 'imgico';
      img2.src = 'assets/imgs/delete24.png';
      img2._addr = addr;
      img2.onclick = function() {
        del_addr(this._addr);
      }
      td.appendChild(img2);
    } 
  }
  
  function save_addr(addr, elm) {
    var pos, width, height;
    width = 600;
    height = 330;
    pos = [400, MyUtils.findPos(elm)[1] - 100];
    var address = (addr) ? addr : init_addr();
    var func = function(option) {
      $.ajax({
        type: "POST",
        url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
        data: "action=save_addr&q=" + encodeURIComponent(JSON.stringify(option)),
        success: function(msg){
          _addrs = JSON.parse(msg);
          set_customer_addr();
        }
      });
    }
    new ADDR(width, height, pos, address, func);
  }

  function set_addr_default(addr) {
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=set_default&q=" + encodeURIComponent(JSON.stringify(addr)),
      success: function(msg){
        _addrs = JSON.parse(msg);
        set_customer_addr();
      }
    });
  }

  function check_save() {
    if (!_item || _item.account != $('#account')[0].value) {
      CheckUtils.addToArray(_checks_add, $('#account')[0], check_account, _errors_add);
    }
    save();
  }
  
  function save() {
    if (_checks_add.length > 0) {
      setTimeout('save();', 500);
      return;
    }
    if (_errors_add.length > 0) {
      return;
    }
    var obj = {
      <?php if ($item) { ?>
      id: '<?php echo $item->id; ?>',
      <?php } else { ?>
      _id: '<?php echo $min_id; ?>',
      <?php } ?>
      track_id: MyUtils.getUnique(),
      account: document.getElementById('account').value,
      password: document.getElementById('password').value,
      first_name: document.getElementById('first_name').value,
      last_name: document.getElementById('last_name').value,
      phone: document.getElementById('phone').value,
      is_actived: $('#active_select')[0].options[$('#active_select')[0].selectedIndex].value,
      member_id: $('#member_select')[0].options[$('#member_select')[0].selectedIndex].value,
      ip: document.getElementById('ip').value,
      ip_place: document.getElementById('ip_place').value
    }
    if (_pwchg == 1) {
      obj._password = obj.password;
    }
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=save_customer&q=" + encodeURIComponent(JSON.stringify(obj)),
      success: function(msg){
        var obj = JSON.parse(msg);
        parent.location.href = 'http://<?php echo URL . "admin.php?i=$page_id&script=index_customer&id="; ?>' + obj.id;
      }
    });
  }

  function del_addr(addr) {
    r = window.confirm('Are You Sure?');
    if (!r) {
      return;
    }
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=del_addr&q=" + encodeURIComponent(JSON.stringify(addr)),
      success: function(msg){
        _addrs = JSON.parse(msg);
        set_customer_addr();
      }
    });
  }
  
  function init_addr() {
    var addr = { customer_id: '<?php  echo ($item) ? $item->id : $min_id; ?>',
                 first_name: _item.first_name,
                 last_name: _item.last_name,
                 address1: '',
                 address2: '',
                 city: '',
                 country: '',
                 zip: '',
                 phone: _item.phone,
                 email: _item.account,
                 is_default: 1
               }
    return addr;
  }

  function check_account(inputElm, callbackFunc, errorArr) {
    if (inputElm.value == '') {
      CheckUtils.addError(inputElm, errorArr, 'Required');
      callbackFunc();
      return;
    } else {
      var re = /^[a-zA-Z0-9]([a-zA-Z0-9]*[-_.]?[a-zA-Z0-9]+)+@([a-zA-Z0-9]+\.)+[a-zA-Z]{2,}$/;
      if (!re.test(inputElm.value)) {
        CheckUtils.addError(inputElm, errorArr, 'Not a proper email');
        callbackFunc();
        return;
      } else {
        $.ajax({
          type: "POST",
          url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
          data: "action=check_account&q=" + encodeURIComponent(inputElm.value),
          success: function(msg){
            var tmp = JSON.parse(msg);
            if (tmp.result == 0) {
              CheckUtils.addError(inputElm, errorArr, 'Account is used');
            }
            callbackFunc();
          }
        });
        return;
      }
    }
    callbackFunc();
  }
  
</script>
</body>
</html>